import path from 'path';
import fs from 'fs';
import moment from 'moment';
/**
 * 随机数函数
 * @param min 最小值
 * @param max 最大值
 */
export function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


/**
 * 休眠函数
 * @param ms 毫秒
 */
export async function sleep(ms = 500) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

//创建文件夹
export function createDir(filename) {
  const uploadPath = path.resolve(process.cwd(), 'plugins/tg-plugin/resources/video');
  const dirname = moment(Date.now()).format('YYYY/MM/DD')
  const mkdirsSync = dirname => {
    if (fs.existsSync(dirname)) {
      return true
    } else {
      if (mkdirsSync(path.dirname(dirname))) {
        fs.mkdirSync(dirname)
        return true
      }
    }
  }
  mkdirsSync(path.join(uploadPath, dirname))
  const filepath = path.join(uploadPath, dirname, filename)
  return {
    filepath,
    dirname: path.join(uploadPath, dirname),
    filename
  }
}
export class HourlyRateLimiter {
  constructor() {
    this.limiterMap = new Map();
  }

  canTrigger(id, limitPerHour, time = 3600000) {
    if (!this.limiterMap.has(id)) {
      this.limiterMap.set(id, {
        limitPerHour,
        events: [],
      });
    }

    const limiter = this.limiterMap.get(id);
    const currentTime = Date.now();
    limiter.events = limiter.events.filter(event => currentTime - event < time);

    if (limiter.events.length < limiter.limitPerHour) {
      limiter.events.push(currentTime);
      return true;
    }

    return false;
  }
}